﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization;
using System.Collections;
using System.Xml.Serialization;
using System.Security.Cryptography;

namespace Admin
{
    public partial class Form1 : Form
    {
        List<loginVisual> lLogin;
        public Form1()
        {
            InitializeComponent();
        }
        static string getMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();
            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();
            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        // Verify a hash against a string.
        static bool verifyMd5Hash(string input, string hash)
        {
            // Hash the input.
            string hashOfInput = getMd5Hash(input);
            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                if (Directory.Exists(folderBrowserDialog1.SelectedPath))
                {
                    if (File.Exists(folderBrowserDialog1.SelectedPath + "\\" + "Users.xml"))
                    {
                        XmlSerializer xml;
                        FileStream stream;
                        xml = new XmlSerializer(typeof(List<login>));
                        stream = new FileStream(folderBrowserDialog1.SelectedPath + "\\" + "Users.xml", FileMode.Open, FileAccess.Read);
                        List<login> u = (List<login>)xml.Deserialize(stream);
                        stream.Close();
                        lLogin=new List<loginVisual>();
                        foreach (login l in u)
                        {
                            loginVisual t = new loginVisual();
                            t.user = l.user;
                            t.pass = l.pass;
                            int type=2;
                            if (verifyMd5Hash(l.user + l.pass + "1", l.type)) type = 1;
                            if (verifyMd5Hash(l.user + l.pass + "0", l.type)) type = 0;
                            if (type == 1)
                            {
                                t.type = "Только просмотр";
                                lLogin.Add(t);
                            }
                            if (type == 0)
                            {
                                t.type = "Полные";
                                lLogin.Add(t);
                            }
                        }
                        show_user();

                    }
                    else
                        MessageBox.Show("Выбранная папка не содержит корректную БД");
                }
            }
        }

        private void show_user()
        {
            treeView1.Nodes.Clear();
            treeView1.Nodes.Add("♀Полные", "Полные права");
            treeView1.Nodes.Add("♀Только просмотр", "Только просмотр");
            foreach (loginVisual t in lLogin)
            {
                foreach (TreeNode f in treeView1.Nodes)
                    if (f.Name == ("♀"+t.type))

                        f.Nodes.Add(t.user, t.user);
            }

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(folderBrowserDialog1.SelectedPath))
            {
                //lLogin = new List<loginVisual>();
                if (lLogin!=null)
                {
                    List<login> u = new List<login>();
                    foreach (loginVisual t in lLogin)
                    {
                        login l = new login();
                        l.user = t.user;
                        l.pass = t.pass;
                        if (t.type == "Только просмотр")
                            l.type = getMd5Hash(l.user + l.pass + "1");
                        if (t.type == "Полные")
                            l.type = getMd5Hash(l.user + l.pass + "0");
                        u.Add(l);
                    }


                    XmlSerializer xml;
                    FileStream stream;
                    xml = new XmlSerializer(typeof(List<login>));
                    stream = new FileStream(folderBrowserDialog1.SelectedPath + "\\" + "Users.xml", FileMode.Create, FileAccess.ReadWrite);
                    xml.Serialize(stream, u);
                    stream.Close();
                    
                    

                }
            }

        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Name.IndexOf("♀") < 0)
                foreach (loginVisual l in lLogin)
                    if (l.user == e.Node.Name)
                        propertyGrid1.SelectedObject = l;
        }

        private void propertyGrid1_Validated(object sender, EventArgs e)
        {
            show_user();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (lLogin != null)
            {
                loginVisual l = new loginVisual();
                l.user = "user";
                l.passv = "pass";
                l.type = "Только просмотр";
                lLogin.Add(l);
                show_user();
            }
        }

        private void propertyGrid1_SelectedGridItemChanged(object sender, SelectedGridItemChangedEventArgs e)
        {
            show_user();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
                if (treeView1.SelectedNode.Name.IndexOf("♀") < 0)
                    foreach (loginVisual l in lLogin)
                        if (l.user == treeView1.SelectedNode.Name)
                        {
                            propertyGrid1.SelectedObjects = null;
                            lLogin.Remove(l);
                            show_user();
                            break;
                            
                        }

        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            show_user();
        }

        public void val(string s)
        {
            if (s != DateTime.Now.ToShortDateString()) Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Form2 f = new Form2();
            f.main = this;
            f.ShowDialog();
        }
    }
}
